import React, { Component } from 'react';
import {  Alert,FlatList, TouchableOpacity,ActivityIndicator,StyleSheet, Text, View } from 'react-native';

export default class FlatListBasics extends Component {


  constructor(props) {
    super(props)
    this.state = { data: [] }
  }


      componentDidMount(){
        return fetch('https://jsonplaceholder.typicode.com/posts')
          .then((response) => response.json())
          .then((responseJson) => {

            this.setState({
              isLoading: false,
              data: responseJson,
            }, function(){
                console.log("callback")
            });
          })
          .catch((error) =>{
                Alert.alert('error:'+error)
          });
      }
    _onPressButton =(item)=> {
      Alert.alert('click item.value:'+item.body.slice(5,15))
    }


  render() {

      if(this.state.isLoading){
        return(
          <View style={{flex: 1, padding: 10}}>
            <ActivityIndicator/>
          </View>
        )
      }
    console.warn('Test log ,C:\\react_native\\Android_Study\\First\\LongList.js')
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          keyExtractor={item => item.id.toString()}  /* todo 没有KEY 项时的字段 映射* /
          /*renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}*/
          renderItem={({item}) => {
              return(
                <TouchableOpacity  style={styles.item}
                        onPress={() => this._onPressButton(item)}>
                     <Text >{item.title.slice(5,15)}</Text>
                </TouchableOpacity>
              )
            }
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})